package com.sh.apibackend.provider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sh.apibackend.common.ErrorCode;
import com.sh.apibackend.exception.BusinessException;
import com.sh.apibackend.mapper.InterfaceInfoMapper;
import com.sh.apibackend.mapper.UserMapper;
import com.sh.apibackend.model.userinterface.UpdateUserInterfaceInfoDTO;
import com.sh.apibackend.service.InterfaceChargingService;
import com.sh.apibackend.service.UserInterfaceInfoService;
import com.sh.apicommon.entity.InterfaceCharging;
import com.sh.apicommon.entity.InterfaceInfo;
import com.sh.apicommon.entity.User;
import com.sh.apicommon.service.ApiBackendService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;


/**
 * 作为服务提供方，提供远程调用接口
 */
@DubboService
public class ApiBackendServiceImpl implements ApiBackendService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;


    @Resource
    private InterfaceChargingService interfaceChargingService;

    /**
     * 根据accessKey和secretKey获取接口调用用户的信息，判断其是否有权限
     * @param accessKey
     * @return
     */
    @Override
    public User getInvokeUser(String accessKey) {
        if (StringUtils.isBlank(accessKey)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("accessKey", accessKey);
        User user = userMapper.selectOne(userQueryWrapper);
        return user;
    }

    @Override
    public InterfaceInfo getInterFaceInfo(String url, String method) {
        if ( StringUtils.isBlank(url) || StringUtils.isBlank(method)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> interfaceInfoQueryWrapper = new QueryWrapper<>();
        interfaceInfoQueryWrapper.eq("url", url);
        interfaceInfoQueryWrapper.eq("method", method);
        InterfaceInfo interfaceInfo = interfaceInfoMapper.selectOne(interfaceInfoQueryWrapper);
        return interfaceInfo;
    }

    @Override
    public boolean invokeCount(long userId, long interfaceInfoId) {
        boolean result = userInterfaceInfoService.invokeCount(userId, interfaceInfoId);
        return result;
    }

    @Override
    public int getLeftInvokeCount(long userId, long interfaceInfoId) {
        return 0;
    }


    /**
     * 提供根据接口id获取接口信息
     * @param interfaceId
     * @return
     */
    @Override
    public InterfaceInfo getInterfaceById(long interfaceId) {
        return interfaceInfoMapper.selectById(interfaceId);
    }


    /**
     * 获取接口库存, 即用户购买时先看看我的库存够不够
     * @param interfaceId
     * @return
     */
    @Override
    public int getInterfaceStockById(long interfaceId) {
        QueryWrapper< InterfaceCharging> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interfaceId", interfaceId);
        InterfaceCharging one = interfaceChargingService.getOne(queryWrapper);
        if ( one==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询不到该接口");
        }
        String availablePieces = one.getAvailablePieces();
        return Integer.parseInt(availablePieces);
    }

    @Override
    public boolean updateInterfaceStock(long interfaceId, Integer num) {
        UpdateWrapper<InterfaceCharging> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceId", interfaceId)
                .setSql("availablePieces=availablePieces- "+num)
                .gt("availablePieces",num);
        boolean updateResult = interfaceChargingService.update(updateWrapper);
        return updateResult;
    }

    @Override
    public boolean recoverInterfaceStock(long interfaceId, Integer num) {
        UpdateWrapper<InterfaceCharging> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("availablePieces = availablePieces + "+num)
                .eq("interfaceId",interfaceId);
        return interfaceChargingService.update(updateWrapper);
    }


    // 用户购买接口后，更新用户的调用次数
    @Override
    public boolean updateUserInterfaceInvokeCount(long userId, long interfaceId, int num) {
        UpdateUserInterfaceInfoDTO updateUserInterfaceInfoDTO = new UpdateUserInterfaceInfoDTO();
        updateUserInterfaceInfoDTO.setUserId(userId);
        updateUserInterfaceInfoDTO.setInterfaceId(interfaceId);
        updateUserInterfaceInfoDTO.setLockNum((long) num);
        boolean result = userInterfaceInfoService.updateUserInterfaceInfo(updateUserInterfaceInfoDTO);
        return result;
    }
}
